<template>
  <el-dialog width="600px" :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
             :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item size='small' label="猪舍" prop="houseId">
            <el-select v-model="dataForm.houseId" @change="house_change" placeholder="猪舍">
              <el-option
                  v-for="(house, house_id) in houses"
                  :key="house_id"
                  :label="house.name"
                  :value="house_id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="类型" prop="type">
            <el-select v-model="dataForm.type" placeholder="类型">
              <el-option label="种猪" value="种猪"></el-option>
              <el-option label="生长猪" value="生长猪"></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item size='small' label="销售日期" prop="salesDate">
            <el-date-picker
                v-model="dataForm.salesDate"
                align="right"
                type="date"
                placeholder="销售日期"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="销售类型" prop="salesType">
            <el-select v-model="dataForm.salesType" placeholder="类型">
              <el-option label="正常销售" value="正常销售"></el-option>
              <el-option label="淘汰销售" value="淘汰销售"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="栏位" prop="grid">
            <el-select size='mini' style="width: 90px" v-model="dataForm.grid.row" placeholder="行">
              <el-option
                v-for="item in rows"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select size='mini' style="width: 90px" v-model="dataForm.grid.column" placeholder="列">
              <el-option
                v-for="item in columns"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="单价" prop="unitFee">
            <el-input v-model="dataForm.unitFee" placeholder="单价" type="number"><i slot="suffix" style="font-style:normal;margin-right: 10px;">元/kg</i></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="单位" prop="unit">
            <el-input v-model="dataForm.unit" placeholder="单位"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="重量" prop="weight">
            <el-input v-model="dataForm.weight" placeholder="重量" type="number"><i slot="suffix" style="font-style:normal;margin-right: 10px;">kg</i></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="数量" prop="mounts">
            <el-input v-model="dataForm.mounts" placeholder="数量"><i slot="suffix" style="font-style:normal;margin-right: 10px;">头</i></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="总价" prop="price">
            <el-input v-model="dataForm.price" placeholder="总价"><i slot="suffix" style="font-style:normal;margin-right: 10px;">元</i></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="操作人" prop="operatorName">
            <UserSelect v-model="dataForm.operatorName"></UserSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="原因" prop="reason">
            <el-input v-model="dataForm.reason" placeholder="原因"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item size='small' label="备注" prop="remark">
            <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <Grid v-if="dataForm.houseId" type="1" v-on:gridSelect="gridSelect" :house_id="dataForm.houseId"></Grid>
    <template slot="footer">
      <el-col :span="4">
        <el-checkbox label="连续录入" v-model="continues"></el-checkbox>
      </el-col>
      <el-col :span="20">
        <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
      </el-col>
    </template>
  </el-dialog>
</template>

<script>
/* eslint-disable */
import debounce from 'lodash/debounce'

export default {
  data() {
    return {
      visible: false,
      continues: true,
      dataForm: {
        id: '',
        houseId: '',
        houseName: '',
        type: '生长猪',
        salesDate: '',
        grid: {row: '', column: ''},
        price: '',
        unitFee: '',
        unit: '',
        earmark: '',
        weight: '',
        remark: '',
        mounts: '',
        reason: '',
        operatorName: '',
        salesType: '',
      },
      houses: {},
      rows: [],
      columns: [],
      pickerOptions: {
        disabledDate: (time) => {
            var year1=new Date(time).getFullYear();
				    var year2=new Date().getFullYear();
            return time.getTime() > Date.now() || (year2-year1 >= 5);
        }
      }
    }
  },
  computed: {
    dataRule() {
      return {
        houseId: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        houseName: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        type: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        salesDate: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
      }
    }
  },
  created() {
    this.getHouses()
  },
  methods: {
    gridSelect (grid) {
      console.table(grid)
      this.dataForm.grid.row = grid.row
      this.dataForm.grid.column = grid.column
      this.$forceUpdate()
    },
    init () {
      let that = this
      this.visible = true
      this.$nextTick(() => {
        if (!this.dataForm.id) {
          this.$refs['dataForm'].resetFields()
          that.$forceUpdate()
        }
        that.getHouses()
      })
    },
    house_change() {
      let house = this.houses[this.dataForm.houseId]
      this.rows = []
      this.columns = []
      for (let i=0; i<house.rows; ++i) {
        this.rows.push({
          value: i+1,
          label: i+1+'行'
        })
      }
      for (let i=0; i<house.columns; ++i) {
        this.columns.push({
          value: i+1,
          label: i+1+'列'
        })
      }
    },
    getHouses () {
      let that = this;
      this.$http.get(`/basic/house/all`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        res.data.forEach(function(house){
          that.houses[house.id] = house;
        });
        that.house_change()
        that.$forceUpdate()
      }).catch(() => {})   
    },
    // 获取信息
    getInfo() {
      this.$http.get(`/sales/sales/${this.dataForm.id}`).then(({data: res}) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {
      })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.dataForm.grid = this.dataForm.grid.row + '-' + this.dataForm.grid.column;
        this.$http[!this.dataForm.id ? 'post' : 'put']('/sales/sales/', this.dataForm).then(({data: res}) => {
          if (res.code !== 0) {
            this.dataForm.grid = {row:'', column:''};
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              if(!this.continues) {
                this.visible = false
              } else {
                for(let key in this.dataForm) {
                  this.dataForm[key] = '';
                }
                this.dataForm.grid = {row:'', column:''};
              }
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {
        })
      })
    }, 1000, {'leading': true, 'trailing': false})
  }
}
</script>
<style scoped>
    .el-input, .el-select {
      width: 180px;
    }

    .el-textarea {
      width: 460px;
    }
</style>